package com.dayuanit.booksystem.v3.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MybatisUtil {

    //每一个应用有一个sqlsessionFactory
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * mybatis框架初始化
     * 初始化：只会执行一次，而且是系统在启动时，自动执行，为程序提供响应的初始数据。
     * @throws Exception
     */
    private static void init() throws Exception {
        String xmlPath  = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(xmlPath);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    /**
     * sqlSession默认开启事务的
     * @return
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }

    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }

}
